package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.project.bean.ShopBean;
import com.project.mapper.IShopMapper;
import com.project.service.IShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class ShopServiceImpl implements IShopService {
    @Autowired
    private IShopMapper mapper;
    @Override
    public List<ShopBean> findByUser(Integer userId) {

        return mapper.findByUser(userId);
    }

    @Override
    public void add(Integer userId, Integer productId) {
        QueryWrapper<ShopBean> qw = new QueryWrapper<>();
        qw.eq("fk_userId",userId);
        qw.eq("fk_productId",productId);

        ShopBean shop = mapper.selectOne(qw);
        if(shop != null){//商品存在，购买数量加一
            shop.setNum(shop.getNum() + 1);
            mapper.updateById(shop);
        }
        else{//商品不存在，新加记录
            shop = new ShopBean();
            shop.setProductId(productId);
            shop.setUserId(userId);
            shop.setNum(1);
            mapper.insert(shop);
        }
    }

    @Override
    public void del(Integer id) {
        mapper.deleteById(id);
    }

    @Override
    public void updateNum(Integer id, Integer num) {
        ShopBean shopBean = mapper.selectById(id);
        shopBean.setNum(num);
        mapper.updateById(shopBean);
    }
}
